package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.service.ApArticleService;
import com.heima.common.constant.GlobalConstant;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dots.ArticleDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.service.ApArticleContentService;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApArticleContentServiceImpl extends ServiceImpl<ApArticleContentMapper, ApArticleContent> implements ApArticleContentService {
    @Autowired
    Configuration configuration;
    @Autowired
    FileStorageService fileStorageService;
    @Autowired
    ApArticleService apArticleService;
    @Override
    public String generateContentHtml(ApArticleContent articleContent) throws IOException, TemplateException {
        Template template = configuration.getTemplate("article.ftl");
        Map<String, Object> map=new HashMap<>();
        map.put("content", JSONArray.parseArray(articleContent.getContent()));
        StringWriter stringWriter=new StringWriter();
        template.process(map,stringWriter);
        ByteArrayInputStream inputStream=new ByteArrayInputStream(stringWriter.getBuffer().toString().getBytes());
        String url = fileStorageService.uploadHtmlFile("", articleContent.getArticleId()+".html", inputStream);
        return url;
    }

    @Override
    public void deleteContentHtml(String url) {
        fileStorageService.delete(url);
    }

}
